using System;
using System.Text;
using System.Reflection;
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Crainiate.Data.Persistence;
using Crainiate.Data.Persistence.Cache;
using Crainiate.Data.Persistence.Providers;
using Crainiate.Data.Persistence.Providers.SqlServer;

namespace Crainiate.Data.Persistence.Testing
{
    [TestClass]
    public class DeploymentTests
    {
        //Initialise test class
        [ClassInitialize()]
        public static void ClassInitialize(TestContext testContext)
        {

        }

        //Simulate multiple deployments of the same class with no data
        [TestMethod]
        public void Deploy()
        {
            Context context = Component.Instance.GetContext();
            Deployment deployment = Component.Instance.CreateDeployment();
            deployment.Context = context;

            //Validate the assembly against the database
            deployment.DeploymentType = Crainiate.Data.Persistence.Providers.DeploymentType.Deploy;
            deployment.DeploymentMode = Crainiate.Data.Persistence.Providers.DeploymentMode.Update;
            deployment.PreDeployType += new Crainiate.Data.Persistence.Providers.PreDeployTypeHandler(deployment_PreDeployType);

            for (int i = 1; i <= 6; i++)
            {
                context.Prefix = "Crainiate.Data.Persistence.Testing.Step" + i;
                deployment.Deploy(System.Reflection.Assembly.GetExecutingAssembly());
            }

            //Deploy with data
            //StringBuilder builder = new StringBuilder();
            //builder.Append("DROP TABLE Entity");
            //deployment.Execute(builder);

            //for (int i = 1; i <= 6; i++)
            //{
            //    context.Prefix = "Crainiate.Data.Persistence.Testing.Step" + i;
            //    deployment.Deploy(System.Reflection.Assembly.GetExecutingAssembly());

            //    //Add some data for step 1
            //    if (i == 1)
            //    {
            //        Crainiate.Data.Persistence.Testing.Step1.Entity entity = new Crainiate.Data.Persistence.Testing.Step1.Entity();

            //        entity.Context = context;
            //        entity.Id = 1;
            //        entity.Insert();
            //    }
            //}
        }

        //Only deploy types that are authorised
        private void deployment_PreDeployType(object sender, Crainiate.Data.Persistence.Providers.PreDeployTypeEventArgs e)
        {
            Deployment deployment = sender as Deployment;
            if (!e.Type.FullName.StartsWith(deployment.Context.Prefix)) e.Cancel = true;
        }
    }
}
